package com.wkbb.basic.service.impl;

import com.wkbb.basic.mapper.OrgStructureMapper;
import com.wkbb.basic.mapper.OrgStructureUserMapper;
import com.wkbb.basic.model.OrgStructure;
import com.wkbb.basic.service.OrgStructureService;
import com.wkbb.common.base.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author lizhichao
 * @date 2019/8/9
 * @description
 */
@Service
@Slf4j
public class OrgStructureServiceImpl extends BaseServiceImpl<OrgStructure> implements OrgStructureService {

    @Autowired
    OrgStructureMapper orgStructureMapper;
    @Autowired
    OrgStructureUserMapper orgStructureUserMapper;

    @Autowired
    public void setMapper(OrgStructureMapper mapper) {
        super.setMapper(mapper);
    }

    @Override
    public List<OrgStructure> initOrgStructureTreeList(Map<String, Object> params) throws Exception {
        return this.orgStructureMapper.initOrgStructureTreeList(params);
    }

    @Override
    public List<OrgStructure> getOrgStructureTreeList(Map<String, Object> params) throws Exception {
        return this.orgStructureMapper.getOrgStructureTreeList(params);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteOrgStructureBatch(Long parentId, Long orgId) throws Exception {
        Map<String, Object> params = new HashMap();
        params.put("orgId", orgId);
        params.put("parentId", parentId);
        List<OrgStructure> structureTreeList = this.orgStructureMapper.getOrgStructureTreeList(params);
        List<OrgStructure> deleteStructureList = new ArrayList();//用于删除
        //主架构
        OrgStructure mainOrgStructure = new OrgStructure();
        mainOrgStructure.setId(parentId);
        deleteStructureList.add(mainOrgStructure);
        this.getSubStructure(deleteStructureList, structureTreeList);
        //批量删除组织架构及其子架构
        this.orgStructureMapper.deleteBatch(deleteStructureList);
        //批量删除子节点挂的用户数据
        this.orgStructureUserMapper.deleteStructureUsersBatch(deleteStructureList);
    }

    /**
     * 迭代获取子节点
     * @param deleteStructureList
     * @param structureTreeList
     */
    private void getSubStructure(List<OrgStructure> deleteStructureList, List<OrgStructure> structureTreeList) {
        Iterator iterator = structureTreeList.iterator();

        while (iterator.hasNext()) {
            OrgStructure orgStructure = (OrgStructure) iterator.next();
            deleteStructureList.add(orgStructure);
            if (orgStructure.getChildren().size() > 0) {
                this.getSubStructure(deleteStructureList, orgStructure.getChildren());
            }
        }

    }
}